#!/user/bin/even Python3
# -*- coding:utf-8 -*-
# Run.py
# 
# author:zhaohexin
# time：2020/7/29 10:57
import sys

from PyQt5.QtCore import Qt, pyqtSignal, QThread
from PyQt5.QtWidgets import QMainWindow, QApplication, QCompleter, QMessageBox, QFileDialog
from LdlCodeSearch import Ui_Form
from utility.HistorySave import SaveHistory
from utility.GetUrlDatas import GetUrlDatas
from conf import SendHistory
from utility.GetExcelData import GetExcelData
from utility.CreateFile import CreateFlie


class Worker(QThread):
    progressBarValue = pyqtSignal(int)  # 更新进度条
    progressBarBox = pyqtSignal(str)  # 更新进度条

    def __init__(self):
        super(Worker, self).__init__()

    def run(self):
        # 页面数据读取
        ui_datas = myWin.get_ui_data()
        # 判断excel文件路径是否存在，若存在，则不用输入的条件查询，若不存在，则查询
        if ui_datas.get("excel_path"):
            # 读取excel文件组成数据组进行
            url_condition = GetExcelData().get_data()
        else:
            url_condition = [
                {"ID": "1", "search_industry": ui_datas.get("search_industry"), "search_career": ui_datas.get("search_career")}]
        # 获取接口返回数据
        datas = GetUrlDatas(url_condition, myWin, self.progressBarValue).get_datas()
        # 进行数据存储
        CreateFlie(datas, myWin, self.progressBarValue, self.progressBarBox).save()


class MyWindow(QMainWindow, Ui_Form):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)
        self.setupUi(self)
        self.history_datas = self.save_history({})
        self.init_url()
        self.init_career()
        self.init_path()
        self.init_industry()

    def get_ui_data(self):
        """
        获取页面数据
        :return: 页面数据字典
        """
        search_url = self.lineEdit.text()
        search_industry = self.lineEdit_2.text()
        excel_path = self.lineEdit_3.text()
        search_career = self.lineEdit_4.text()
        return {
            "search_url": search_url,
            "search_industry": search_industry,
            "excel_path": excel_path,
            "search_career": search_career,
        }

    def save_history(self, ui_datas):
        """
        存储输入历史记录
        :return:
        """
        # 进行配置文件留存
        SendHistory.search_url = ui_datas.get("search_url")
        SendHistory.search_industry = ui_datas.get("search_industry")
        SendHistory.excel_path = ui_datas.get("excel_path")
        SendHistory.search_career = ui_datas.get("search_career")
        return SaveHistory().save()

    def init_url(self):
        """
        url自动补全
        :return:
        """

        # 增加自动补全
        self.completer = QCompleter(self.history_datas["SEARCH"]["search_url"])
        # 设置匹配模式 有三种： Qt.MatchStartsWith 开头匹配（默认） Qt.MatchContains 内容匹配 Qt.MatchEndsWith 结尾匹配
        self.completer.setFilterMode(Qt.MatchContains)
        # 设置补全模式 有三种： QCompleter.PopupCompletion（默认） QCompleter.InlineCompletion  QCompleter.UnfilteredPopupCompletion
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        # 给lineedit设置补全器
        self.lineEdit.setCompleter(self.completer)

    def init_industry(self):
        """
        industry自动补全
        :return:
        """

        # 增加自动补全
        self.completer = QCompleter(self.history_datas["SEARCH"]["search_industry"])
        # 设置匹配模式 有三种： Qt.MatchStartsWith 开头匹配（默认） Qt.MatchContains 内容匹配 Qt.MatchEndsWith 结尾匹配
        self.completer.setFilterMode(Qt.MatchContains)
        # 设置补全模式 有三种： QCompleter.PopupCompletion（默认） QCompleter.InlineCompletion  QCompleter.UnfilteredPopupCompletion
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        # 给lineedit设置补全器
        self.lineEdit_2.setCompleter(self.completer)

    def init_career(self):
        """
        career自动补全
        :return:
        """

        # 增加自动补全
        self.completer = QCompleter(self.history_datas["SEARCH"]["search_career"])
        # 设置匹配模式 有三种： Qt.MatchStartsWith 开头匹配（默认） Qt.MatchContains 内容匹配 Qt.MatchEndsWith 结尾匹配
        self.completer.setFilterMode(Qt.MatchContains)
        # 设置补全模式 有三种： QCompleter.PopupCompletion（默认） QCompleter.InlineCompletion  QCompleter.UnfilteredPopupCompletion
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        # 给lineedit设置补全器
        self.lineEdit_4.setCompleter(self.completer)

    def init_path(self):
        """
        path自动补全
        :return:
        """

        # 增加自动补全
        self.completer = QCompleter(self.history_datas["SEARCH"]["excel_path"])
        # 设置匹配模式 有三种： Qt.MatchStartsWith 开头匹配（默认） Qt.MatchContains 内容匹配 Qt.MatchEndsWith 结尾匹配
        self.completer.setFilterMode(Qt.MatchContains)
        # 设置补全模式 有三种： QCompleter.PopupCompletion（默认） QCompleter.InlineCompletion  QCompleter.UnfilteredPopupCompletion
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        # 给lineedit设置补全器
        self.lineEdit_3.setCompleter(self.completer)

    def begin(self):
        """
        开始执行查询/存储
        :return:
        """
        # 页面数据读取
        ui_datas = myWin.get_ui_data()
        # 历史记录留存
        myWin.history_datas = myWin.save_history(ui_datas)
        # 自动补全刷新
        myWin.init_url()
        myWin.init_career()
        myWin.init_path()
        myWin.init_industry()
        if SendHistory.search_url:
            if SendHistory.search_career or SendHistory.excel_path or SendHistory.search_industry:
                if SendHistory.is_click:
                    # 上锁
                    SendHistory.is_click = False
                    # 进行item数据组装及文件存储
                    self.thread_1 = Worker()
                    self.thread_1.progressBarValue.connect(self.update_pr)
                    self.thread_1.progressBarBox.connect(self.update_pr_box)
                    self.thread_1.start()
                else:
                    QMessageBox.warning(self, "警告", self.tr("正在执行，请稍后在试。"))
            else:
                QMessageBox.warning(self, "警告", self.tr("查询条件（行业）/查询条件（职业）/Excel文件目录至少填写一项。"))
        else:
            QMessageBox.warning(self, "警告", self.tr("请填写url"))

    def update_pr(self, i):
        self.progressBar.setValue(i)

    def update_pr_box(self, i):
        if i:
            QMessageBox.information(self, "提示", self.tr(f"文件写入完成，请于{SendHistory.save_path}路径下查看"))
            SendHistory.is_click = True

    def check_dir(self):
        """
        实现选择文件夹后向相应的LineEdit赋值
        :param LineEdit:
        :return:
        """
        file = QFileDialog.getOpenFileName(self, 'open file', '/')
        if file[0]:
            if file[0].split(".")[-1] == "xlsx":
                self.lineEdit_3.setText(file[0])
            else:
                QMessageBox.warning(self, "警告", self.tr("只接受.xlsx格式的文件哦！"))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWin = MyWindow()
    myWin.show()

    myWin.pushButton.clicked.connect(myWin.begin)
    myWin.pushButton_2.clicked.connect(myWin.check_dir)

    sys.exit(app.exec_())
